<template>
  <div class="goods-container">
    <nut-searchbar v-model="val" @clear="OnClear" placeholder="在200万+货源信息里搜索看看">
      <template #rightin>
        <nut-button color="#5232b7" size="small" style="margin-right: 6px" @click="onSearch">搜索</nut-button>
      </template>
    </nut-searchbar>
    <Filter :isSelected="isSelected" :tabList="filterList" @onChange="getTabs"></Filter>
    <div class="goods-list-container">
      <scroll-view scroll-y class="good-scroll" v-if="list.length > 0" scrollAnchoring @scrolltolower="onScrollBottom">
        <div class="sestion1">
          <div class="item" v-for="(item, index) in leftColumnItems" @click="toDetail(item)" :key="index">
            <img v-lazy="item.image" alt="" style="width: 100%; height: 60%" />
            <div class="product-title txt">
              {{ item.title }}
            </div>
            <!-- <div class="tags">
              <div class="tag-item">24小时发货</div>
              <div class="tag-item">七天无理由退货</div>
            </div> -->
            <div class="price-box">
              <div class="price-ipt">
                <nut-price v-if="item.productSpecials.length" :price="item.productSpecials[0].sellerPrice / 100"
                  size="normal" />
                <nut-price v-else :price="item.sellPrice / 100" size="normal" />
              </div>
            </div>
          </div>
        </div>
        <div class="sestion2">
          <div class="item" v-for="(item, index) in rightColumnItems" @click="toDetail(item)" :key="index">
            <img v-lazy="item.image" alt="" style="width: 100%; height: 60%" />
            <div class="product-title txt">
              {{ item.title }}
            </div>
            <!-- <div class="tags">

              <div class="tag-item" v-if="item.tags.indexOf(1) !== -1">
                描述不符包退
              </div>
              <div class="tag-item" v-if="item.tags.indexOf(2) !== -1">
                二十四小时发货
              </div>
              <div class="tag-item" v-if="item.tags.indexOf(3) !== -1">
                四十八小时发货
              </div>
              <div class="tag-item" v-if="item.tags.indexOf(4) !== -1">
                假货包赔
              </div>
            </div> -->
            <div class="price-box">
              <div class="price-ipt">
                <nut-price v-if="item.productSpecials.length" :price="item.productSpecials[0].sellerPrice / 100"
                  size="normal" />
                <nut-price v-else :price="item.sellPrice / 100" size="normal" />
              </div>
            </div>
          </div>
        </div>
      </scroll-view>
      <!-- <Loading :page="searchParams.currentPage" :total="totalPage" :loadingFlag="loadingFlag" :tipFlag="tipFlag">
      </Loading> -->
      <template v-else-if="list.length === 0 && !loading">
        <div style="width: 100%; text-align: center">
          <nut-empty description="无数据"></nut-empty>
        </div>
      </template>
      <template v-else-if="list.length === 0 && loading">
        <nut-skeleton :style="{ width: '100%', height: '500px', margin: '0.5rem 0.5rem' }" title animated row="3">
        </nut-skeleton>
        <nut-skeleton :style="{ width: '100%', height: '500px', margin: '0.5rem 0.5rem' }" title animated row="3">
        </nut-skeleton>
        <nut-skeleton :style="{ width: '100%', height: '500px', margin: '0.5rem 0.5rem' }" title animated row="3">
        </nut-skeleton>
        <nut-skeleton :style="{ width: '100%', height: '500px', margin: '0.5rem 0.5rem' }" title animated row="3">
        </nut-skeleton>
        <nut-skeleton :style="{ width: '100%', height: '500px', margin: '0.5rem 0.5rem' }" title animated row="3">
        </nut-skeleton>
        <nut-skeleton :style="{ width: '100%', height: '500px', margin: '0.5rem 0.5rem' }" title animated row="3">
        </nut-skeleton>
      </template>
    </div>
  </div>
  <Tabbar></Tabbar>
</template>
<script setup>
import Tabbar from "../../component/Tabbar";
import Filter from "./components/filter/index.vue";
import { onMounted, computed, nextTick } from "vue";
import { storeToRefs } from "pinia";
import Loading from "../../component/Loading/index.vue";
import Taro, { useDidShow } from "@tarojs/taro";
import { useTabbarStore } from "../../store";
import * as productApi from "../../api/product";
const tabbarStore = useTabbarStore();
const { selected, tabbarHeight } = storeToRefs(tabbarStore);
import { ref } from "vue";
const filterList = ref([]);
// const leftColumnItems = computed(() => {
//   const mid = Math.ceil(list.value.length / 2);
//   return list.value.slice(0, mid);
// });

// const rightColumnItems = computed(() => {
//   const mid = Math.ceil(list.value.length / 2);
//   return list.value.slice(mid);
// });

const leftColumnItems = ref([]);
const rightColumnItems = ref([]);
const val = ref("");
const isSelected = ref(0);
const list = ref([]);

const searchParams = ref({
  currentPage: 1,
  pageSize: 10,
  cateId: 0,
});
const loading = ref(false); // 加载状态
const totalPage = ref(0); //总页数
const loadingFlag = ref(false);
const tipFlag = ref(false); // 加载的提示
// const getProductList = async (status) => {
//   try {
//     loading.value = true;
//     const result = await productApi.getProductList(searchParams.value);
//     if (result.state == 200) {
//       if (status) {
//         // 滚动加载更多
//         list.value = [...list.value, ...result.data.list];
//       } else {
//         // 初始加载
//         list.value = result.data.list;
//       }
//       totalPage.value = result.data.pageCount;
//     } else {
//       list.value = [];
//     }
//   } catch (error) {
//     console.error(error);
//   } finally {
//     loading.value = false;
//     loadingFlag.value = false;
//     // 不需要手动调用 splitItems，计算属性会自动更新
//   }
// };

const getProductList = async (status) => {
  try {
    loading.value = true;
    const result = await productApi.getProductList(searchParams.value);
    if (result.state == 200) {
      const newList = status ? [...list.value, ...result.data.list] : result.data.list;
      
      // 分割数据到左右列
      const mid = Math.ceil(newList.length / 2);
      if (status) {
        leftColumnItems.value = [...leftColumnItems.value, ...newList.slice(0, mid)];
        rightColumnItems.value = [...rightColumnItems.value, ...newList.slice(mid)];
      } else {
        leftColumnItems.value = newList.slice(0, mid);
        rightColumnItems.value = newList.slice(mid);
      }
      
      list.value = newList; // 如果需要保留完整列表
      totalPage.value = result.data.pageCount;
    } else {
      leftColumnItems.value = [];
      rightColumnItems.value = [];
      list.value = [];
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
    loadingFlag.value = false;
  }
};
//搜索
const onSearch = () => {
  if (!val.value) {
    return;
  }
  searchParams.value.title = val.value;
  getProductList(0);
};
const OnClear = () => {
  val.value = "";
  searchParams.value.title = "";

  getProductList(0);
};
const toDetail = (item) => {
  Taro.navigateTo({
    url: `/pages/goods-detail/index?id=${item.id}`,
  });
};

//获取类目
const getCateGoryList = async () => {
  try {
    const result = await productApi.getCategoryList();
    console.log(result, "resultresult");
    if (result.state == 200) {
      filterList.value = result.data.map((item) => {
        return {
          name: item.cateName,
          id: item.cateId,
        };
      });
      filterList.value.unshift({
        name: "全部",
        id: 0,
      });
    } else {
      Taro.showToast({
        title: result.message,
        icon: "none",
      });
    }
  } catch (error) {
    console.error(error);
  }
};

const getTabs = (val) => {
  console.log(val, "ppppp");
  searchParams.value.cateId = val.id;
  searchParams.value.currentPage = 1;

  getProductList(0);
};

//分页节流
const throttle = (func, delay) => {
  let lastTime = 0;
  return function () {
    const now = new Date().getTime();
    if (now - lastTime >= delay) {
      func.apply(this, arguments);
      lastTime = now;
    }
  };
};

const onScrollBottom = throttle(() => {
  console.log(123);
  loadingFlag.value = true;
  tipFlag.value = false;
  if (searchParams.value.currentPage < totalPage.value) {
    searchParams.value.currentPage++;
    getProductList(1);
  } else {
    loadingFlag.value = false;
    tipFlag.value = true;
  }
}, 1000);
// 在绑定滚动事件时使用 onScrollBottom
window.addEventListener("scroll", onScrollBottom);

//页面渲染模板
onMounted(() => {
  tabbarStore.setSelected(1);
  loading.value = true;
  getCateGoryList();
  getProductList(0);
});
</script>
<style lang="scss">
.goods-container {
  display: flex;
  flex-direction: column;
  height: 100%;

  .goods-list-container {
    display: flex;
    flex: 1;
    overflow: hidden;
    padding-bottom: 150px;
    /* 根据 Tabbar 高度调整 */

    .good-scroll {
      display: flex;
      padding: 20px;
      flex: 1;

      .sestion1,
      .sestion2 {
        flex: 1;

        .item {
          background-color: #fff;
          border-radius: 10px;
          overflow: hidden;
          height: 500px;

          .product-title {
            font-size: 24px;
            color: #000;
            height: 80px;
          }

          .tags {
            display: flex;
            flex-wrap: wrap;
            margin-top: 15px;
            padding: 0 10px;

            .tag-item {
              background-color: orange;
              padding: 6px;
              border-radius: 5px;
              font-size: 16px;
              color: #fff;
            }

            .tag-item:nth-child(n + 2) {
              margin-left: 10px;
            }
          }

          .txt {
            display: -webkit-box;
            width: 100%;
            /* autoprefixer: ignore next */
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            text-overflow: ellipsis;
            overflow: hidden;
          }
        }
      }

      .sestion1 .item:nth-child(n + 1) {
        margin-top: 15px;
      }

      .sestion2 .item:nth-child(n + 1) {
        margin-top: 15px;
      }

      .sestion1 .item:nth-child(2n) {
        // margin-top: 20px;
        height: 560px;
      }

      .sestion2 .item:nth-child(2n + 1) {

        // margin-top: 20px;
        img {
          height: 80%
        }

        height: 600px;
      }

      .sestion2 {
        margin-left: 15px;
        // margin-top: 40px;
      }
    }
  }
}
</style>
